package cn.tedu.ivos.geofence.service.impl;


import cn.tedu.ivos.base.enums.StatusCode;
import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQueryParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceSaveParam;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQueryParam;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQueryParam geofenceQuery) {
        List<GeofenceVO> geofenceList=geofenceMapper.selectGeofence(geofenceQuery);
        for(GeofenceVO geofenceVO:geofenceList){
            VehicleQueryParam vehicleQueryParam = new VehicleQueryParam();
            vehicleQueryParam.setGeofenceId(geofenceVO.getId());
            List<VehicleVO> vehicleVOS = vehicleMapper.selectVehicle(vehicleQueryParam);
            //获取围栏中绑定的车辆总数
            geofenceVO.setTotalNum(vehicleVOS.size());
            //设置围栏中可用车辆总数
            long availableNum=vehicleVOS
                              .stream()
                              .filter(item->("1").equals(item.getStatus()))
                              .count();
            geofenceVO.setAvailableNum(availableNum);
        }
        return geofenceList;
    }

    @Override
    public void insertGeofence(GeofenceSaveParam geofenceSaveParam) {
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam,geofence);
        Long id = geofenceSaveParam.getId();
        if(id==null){
            geofence.setStatus("1");
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
        }else{
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }

    }

    @Override
    public void deleteById(Long id) {
        VehicleQueryParam vehicleQueryParam=new VehicleQueryParam();
        vehicleQueryParam.setGeofenceId(id);
        List<VehicleVO> vehicleVOS = vehicleMapper.selectVehicle(vehicleQueryParam);
        if(vehicleVOS.size()>0)
            throw new ServiceException("此围栏有车辆绑定，暂时不能删除");
        geofenceMapper.delete(id);
    }
}
